<script lang="ts" setup>
import {
  getListByConditions,
  resetPermissionListByRoleAndMenu,
  selectPermissionTextListByRoleNameAndMenuTitle,
  urls
} from '@/index';
import type { Permission, Menu, Role } from '@/index.d';
import type { CheckboxValueType } from 'element-plus';
import { useRequest } from 'vue-request';

const currentMenu = defineModel<Menu>('currentMenu', { required: true });

const currentRole = defineModel<Role>('currentRole', { required: true });

const getPermissionListByMenuTitlePromise = () => {
  return getListByConditions<Permission>(urls.permission, {
    menuTitle: currentMenu.value.title
  });
};

const getPermissionTextListByRoleNameAndMenuTitlePromise = () => {
  return selectPermissionTextListByRoleNameAndMenuTitle({
    roleName: currentRole.value.name as string,
    menuTitle: currentMenu.value.title
  });
};

const { data: permissionListByMenuTitle, run: getButtonListByMenuTitle } = useRequest(
  getPermissionListByMenuTitlePromise
);

const {
  data: permissionTextListByRoleNameAndMenuTitle,
  run: getButtonTextListByRoleNameAndMenuTitle
} = useRequest(getPermissionTextListByRoleNameAndMenuTitlePromise);

watch(
  () => [currentMenu.value.title, currentMenu.value.isShow],
  value => {
    getButtonListByMenuTitle();
    value[1] && getButtonTextListByRoleNameAndMenuTitle();
  },
  {
    immediate: true
  }
);

const handleChange = (buttonTextList: CheckboxValueType[]) => {
  resetPermissionListByRoleAndMenu({
    roleName: currentRole.value.name as string,
    menuTitle: currentMenu.value.title,
    buttonTextList: buttonTextList as string[]
  });
};
</script>

<template>
  <el-checkbox-group
    v-model="permissionTextListByRoleNameAndMenuTitle"
    @change="handleChange"
    v-if="currentMenu.isShow"
  >
    <el-checkbox-button
      v-for="item in permissionListByMenuTitle"
      :key="item.id"
      :label="item.text"
      :value="item.text"
    />
  </el-checkbox-group>
</template>
<style lang="scss" scoped></style>
